Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.
For example, Given 1->2->3->4, you should return the list as 2->1->4->3.

题目大意:给定链表,交换相邻的2个节点,例如1->2->3->4,交换之后是2->1->4->3,要求空间复杂度O(1),不能改变节点值

题目难度:Easy

/**
 * Created by gzdaijie on 16/5/6
 * 加一个头指针,操作会更方便
 * 当 p.next 和 p.next.next 非空时,交换;p后移2位
 * 这道题考察的是改变指针指向,实现链表节点位置交换
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode h = new ListNode(-1);
        ListNode p = h, q;
        h.next = head;

        while (p.next != null && p.next.next!= null) {
            q = p.next;
            p.next = q.next;
            q.next = p.next.next;
            p.next.next = q;
            p = p.next.next;
        }
        return h.next;
    }
}
gzdaijie            updated 2016-05-18 17:21:37

results matching ""

    No results matching ""